<!-- 模块说明 -->
<style lang="scss" scoped>
.uiComponents-menu {
  width: 100%;

  .uiComponents-menu-item {
    width: 100%;
    height: 40px;
    border-bottom: 1px solid var(--border-color);
    cursor: pointer;
    transition: 0.3s;
    border-radius: 5px;

    &:hover {
      background-color: var(--container-background);
    }
  }
}

.uiComponents {
  &>header {
    font-weight: bold;
    font-size: 22px;
    margin: 10px;
  }

  .uiComponents-body {
    width: 100%;
    position: relative;

    .collapse-tool {
      position: absolute;
      right: 10px;
      top: 10px;
      z-index: 1;
    }
  }
}

.main-body {
  height: 75vh;
  width: 100%;
  overflow: hidden;
  overflow-y: auto;
}

.previewBox {
  position: relative;
  width: 300px;
  height: 200px;

  .maskLayer {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0);
    transition: 0.3s;
    color: rgba(0, 0, 0, 0);
    display: flex;
    align-items: center;
    justify-content: space-around;
    font-size: 18px;

    .icon {
      cursor: pointer;
    }

    .icon:hover {
      color: #54a8ff;
    }

    &:hover {
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
    }
  }
}
</style>
<template>
  <div>
    <FloatWindow type="left">
      <div class="__cards__">
        <div class="uiComponents-menu" v-for="ele in dataList" :key="ele.id">
          <el-text
            truncated
            :class="`uiComponents-menu-item ${ele.id === currentData.id ? '__selectItem__' : ''}`"
            @click="currentData = ele"
            :line-clamp="1"
          >
            <div
              class="__flexCenter__"
              style="height:40px"
            >
              {{ ele.componentName }}
            </div>
          </el-text>
        </div>
      </div>
    </FloatWindow>

    <FloatWindow type="right">
      <el-button :icon="Plus" style="width: 100%; margin: 10px 0" @click="add">
        加一条
      </el-button>
      <el-button :icon="Delete" style="width: 100%; margin: 10px 0" @click="deleteCurrent" type="danger">
        删除当前
      </el-button>
    </FloatWindow>

    <div class="uiComponents">
      <h3>
        技术栈：&nbsp;<el-tag>{{ currentData.type }}</el-tag>
      </h3>
      <br>
      <header>功能说明</header>
      <el-card>
        <div class="uiComponents-body">
          {{ currentData.functionDescription }}
        </div>
      </el-card>

      <header>组件预览</header>
      <el-card>
        <div class="uiComponents-body" style="height: 200px">
          <el-image
            style="width: 100%; height: 200px" :src="currentData.previewUrl"
            :preview-src-list="[currentData.previewUrl]" fit="scale-down"
          />
        </div>
      </el-card>

      <header>参数说明</header>
      <el-card>
        <div class="uiComponents-body" style="height: 200px">
          <TableSimple :columns="columns" :data="currentData.parameter" :show-pagination="false" />
        </div>
      </el-card>

      <header>代码</header>
      <el-card>
        <div class="uiComponents-body" style="height: 500px">
          <div class="collapse-tool">
            <el-button type="primary" @click="copyText(code)" size="small">
              复制代码
            </el-button>
          </div>
          <!-- <el-input type="textarea" :value="currentData.componentCode" :autosize="{ minRows: 22 }" /> -->
          <div style="width: 100%; height: 450px">
            <Codemirror
              :options="{ mode: mode[currentData.type] || 'text/javascript', readOnly: true }" border
              :value="currentData.componentCode" style="width: 100%; height: 450px"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加UI组件弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加组件" width="80%" top="30px">
      <main class="main-body">
        <el-form label-width="80px" :rules="rules" ref="formRefs" :model="editData">
          <el-form-item label="技术类别" prop="type">
            <el-radio-group v-model="editData.type">
              <el-radio value="vue2">
                vue2
              </el-radio>
              <el-radio value="vue3">
                vue3
              </el-radio>
              <el-radio value="react">
                react
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="组件名称" prop="componentName">
            <el-input v-model="editData.componentName" />
          </el-form-item>
          <el-form-item label="功能说明" prop="functionDescription">
            <el-input type="textarea" v-model="editData.functionDescription" :autosize="{ minRows: 5, maxRows: 5 }" />
          </el-form-item>
          <el-form-item label="组件预览" prop="previewUrl">
            <div class="previewBox">
              <img :src="editData.previewUrl" alt="" width="300" height="200" v-if="editData.previewUrl">
              <el-button type="primary" v-else @click="upload">
                上传
              </el-button>
              <div class="maskLayer" v-if="editData.previewUrl">
                <Delete class="icon" @click="editData.previewUrl = ''" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="参数说明" prop="parameter">
            <div style="width: 100%">
              <Tables
                :data="editData.parameter" :columns="editColumns" :show-pagination="false"
                @example="(_d) => (example.fun = _d)"
              />
              <el-button @click="addTableItem" style="margin-top: 10px; width: 100%" :icon="Plus">
                加一条
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="组件代码">
            <div style="width: 100%; height: 350px">
              <Codemirror
                :options="{ mode: 'text/javascript' }" border v-model="editData.componentCode"
                style="width: 98%; height: 350px"
              />
            </div>
          </el-form-item>
        </el-form>
      </main>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">
            关闭
          </el-button>
          <el-button type="primary" @click="onOkDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import 'prismjs/themes/prism-tomorrow.css'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/vue/vue'
import 'codemirror/mode/jsx/jsx'
import Codemirror from 'codemirror-editor-vue3'
import { Plus, Delete } from '@icon-park/vue-next'
import Tables from '@/components/Tables/index.vue'
import TableSimple from '@/components/Tables/TableSimple.vue'
import { onMounted, ref, reactive } from 'vue'
import { uploadFile, addUiComponents, getUiComponentsList, deleteUiComponents } from '@/api/index.js'
import { _uploads, copyText, Message, MessageBox } from '@/utils/index'
import { outputRule } from '@/components/Tables/tool.ts'
const example = reactive({ fun: {} })
const dialogVisible = ref(false)
const mode = {
  vue3: 'text/x-vue',
  vue2: 'text/x-vue',
  react: 'jsx'
}
const editData = reactive({
  type: 'vue2',
  componentName: '',
  functionDescription: '',
  previewUrl: '',
  parameter: [{ attributeName: '', explain: '', type: '', defaultValue: '' }],
  componentCode: `
    /**
     *函数作用  这是一个示例函数
    *@params1 参数含义
    *@params2 参数含义
    */
      function debounce(params1, params2) {
        console.log(params1, params2)
    }
  `
})
const rules = reactive({
  type: [{ required: true }],
  componentName: [{ required: true, message: '请输入组件名称', trigger: 'blur'  }],
  functionDescription: [{ required: true, message: '请输入功能说明', trigger: 'blur' }]
})

const formRefs = ref(null)
const currentData = ref({})
const dataList = ref([])
const columns = [
  {
    title: '属性名',
    dataIndex: 'attributeName'
  },
  {
    title: '说明',
    dataIndex: 'explain'
  },
  {
    title: '类型',
    dataIndex: 'type'
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue'
  }
]
const addTableItem = () => {
  example.fun._add()
}


const editColumns = [
  {
    title: '属性名',
    dataIndex: 'attributeName',
    edit: 'input',
    rules: (row) => {
      if (!row.attributeName) {
        return outputRule('属性名不允许为空', true)
      }
      return outputRule()
    }
  },
  {
    title: '说明',
    dataIndex: 'explain',
    edit: 'input',
    rules: (row) => {
      if (!row.explain) {
        return outputRule('说明不允许为空', true)
      }
      return outputRule()
    }
  },
  {
    title: '类型',
    dataIndex: 'type',
    edit: 'select',
    option: {
      type: 'option',
      data: [
        { label: 'Number', value: 'Number' },
        { label: 'String', value: 'String' },
        { label: 'Object', value: 'Object' },
        { label: 'Function', value: 'Function' },
        { label: 'Array', value: 'Array' },
        { label: 'Boolean', value: 'Boolean' }
      ]
    },
    rules: (row) => {
      if (!row.type) {
        return outputRule('请选择类型', true)
      }
      return outputRule()
    }
  },
  {
    title: '默认值',
    dataIndex: 'defaultValue',
    edit: 'input',
    attrs: {
      type: 'textarea'
    },
    rules: (row) => {
      if (!row.defaultValue) {
        return outputRule('默认值不允许为空', true)
      }
      return outputRule()
    }
  },
  {
    title: '操作',
    render: [
      {
        isName: 'el-button',
        type: 'text',
        text: '删除',
        icon: Delete,
        click(row) {
          // console.log(row.__key__, 'row')
          example.fun._del(row.__key__)
        }
      }
    ]
  }
]

const add = () => {
  dialogVisible.value = true
  formRefs.value.resetFields()
}
const upload = () => {
  _uploads().then(async ([file]) => {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadFile(formData)
    editData.previewUrl = res.data.url
  })
}

const closeDialog = () => {
  dialogVisible.value = false
}
const onOkDialog = async () => {
  const status = await formRefs.value.validate()
  if (!status) return
 
  const parameter = example.fun._get()
  if (!parameter) return

  const data = {
    ...editData,
    parameter
  }
  const res = await addUiComponents(data)
  if (res.code === 200) {
    Message.success('成功')
    closeDialog()
    getComponentsList()
  }
}

const getComponentsList = async () => {
  const res = await getUiComponentsList()
  currentData.value = res.data[0]
  dataList.value = res.data
}

/**
 * 删除当前条
*/
const deleteCurrent = async()=>{
  MessageBox({
    type: 'error',
    title: '提示',
    message: `确认删除"${currentData.value.componentName}"吗?`,
    showCancelButton: true,
    closeOnClickModal: false,
    async callback(val) {
      if (val === 'confirm') {
        const res = await deleteUiComponents({ id: currentData.value.id })
        if (res.code === 200) {
          Message.success('删除成功!')
          getComponentsList()
        }
      }
    }
  })
}

onMounted(async () => {
  getComponentsList()
})
</script>
